/**
 * @author Yura Zhloba
 */
package com.flashdevs.yzh.log
{
import flash.net.LocalConnection;

public class Controller
{
	// properties
	private var model : Model;
	private var lc : LocalConnection;
	private var view : IView;
	private var maxCategoryLength : int = 0;
	private var showLevel : int = LogLevel.INFO.code;
	private var showCategory : String = Model.ALL_CATEGORIES;

	// constructor
	public function Controller(model : Model)
	{
		this.model = model;
	}

	// methods
	public function init(view : IView) : void
	{
		this.view = view;

		lc = new LocalConnection();
		lc.client = this;
		lc.allowDomain("*");

		try
		{
			lc.connect(Model.CONNECTION_NAME);
		}
		catch(e : ArgumentError)
		{
			view.show("Can't connect... the connection name " + Model.CONNECTION_NAME
					+ " is already being used by another SWF");
		}
		catch(e : Error)
		{
			view.show(e.toString());
		}

		view.show("Debug Console started");
	}

	public function setShowLevel(level : int) : void
	{
		if(showLevel == level) return;

		showLevel = level;
		redrawMessages();
	}

	public function setCategory(category : String) : void
	{
		if(showCategory == category) return;

		showCategory = category;
		redrawMessages();
	}

	public function clear() : void
	{
		model.history.length = 0;
		view.clear();
	}

	//noinspection JSUnusedGlobalSymbols
	public function log(level : int, category : String, message : String) : void
	{
		var msg : LogMsg = new LogMsg(level, category, message);
		model.history.push(msg);
		while(model.history.length > model.historyLimit) model.history.shift();

		maxCategoryLength = Math.max(maxCategoryLength, category.length);

		if(!model.categoriesCache[category])
		{
			model.categories.addItem(category);
			model.categoriesCache[category] = true;
		}

		if(level >= showLevel && (showCategory == Model.ALL_CATEGORIES || showCategory == category))
			showLogMsg(msg);
	}

	//noinspection JSUnusedGlobalSymbols
	public function newSession() : void
	{
		// TODO
		view.clear();
	}

	private function redrawMessages() : void
	{
		view.clear();

		for(var i : int = 0; i < model.history.length; i++)
		{
			var msg : LogMsg = model.history[i];
			if(msg.level >= showLevel && (showCategory == Model.ALL_CATEGORIES || showCategory == msg.category))
				showLogMsg(msg);
		}
	}

	private function showLogMsg(msg : LogMsg) : void
	{
		view.show("<p>" + msg.getFormattedLevel() + " " +
				msg.getFormattedCategory(maxCategoryLength) + ": " +
				msg.message + "</p>");
	}

	public function toString() : String
	{ return 'Controller'; }
}
}